<?php
namespace Asiah\SiklusBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Asiah\SiklusBundle\Model\LinkLogic;

class HomeController extends Controller
{
    public function indexAction(Request $request)
    {
	    if($request -> getMethod() == 'POST'){
		    $input = $request->request->get('url');
		    return $this->saveLink($input);
	    }
	    $parameter = array ('result'=>false);
	    return $this -> render('AsiahSiklusBundle:Home:index.html.twig',$parameter);
    }
    private function saveLink($input)
    {
	    $repolink = $this->getDoctrine()->getEntityManager()->getRepository('AsiahSiklusBundle:Link'); 
	    $logic = new LinkLogic();
	    $validate = $logic->validateURL($input);
	    if ($validate){ 
		    $hasil = $repolink->createOrReadLink($input);
		    $this->get('session')->set('url',$hasil->getRealLink());
		    return $this -> render('AsiahSiklusBundle:Home:index.html.twig',array('result'=>'benar', 'short'=>$hasil->getShortLink()));
	    }
	    else
		    return new Response('error');
    }
    public function redirectAction($short)
    {
	    $em = $this -> getDoctrine() -> getEntityManager();
	    $link = $em -> getRepository('AsiahSiklusBundle:Link')->getByShort($short);
	    if($link!=null)
		    return $this->redirect($link->getRealLink());
	    return $this->render('AsiahSiklusBundle::404.html.twig');
    }
}                                       
